<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddOrEdit.visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    style="margin-top: 15vh"
    @close="closeDialog(false)"
  >
    <el-form
      ref="baseFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="80"
      size=""
      style="padding-right: 10px; overflow: auto"
    >
      <el-row justify="center" style="margin-top: 10px">
        <el-col :span="itemSpan">
          <el-form-item label="所属项目" prop="projectName">
            <el-input v-model="formData.projectName" disabled placeholder="请选择" />
            <el-button type="primary" plain style="position: absolute; right: -60px" @click="handleSelectProject"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="所属企业" prop="corpId">
            <el-select v-model="formData.corpId" placeholder="请选择" filterable allow-create clearable>
              <el-option v-for="item in corps" :key="item.corpId" :label="item.name" :value="item.corpId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="开始日期" prop="name">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledStartDate"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledEndDate"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="itemSpan" :offset="0">
          <el-form-item label="状态" prop="endDate">
            <el-radio-group v-model="formData.isDisable" class="ml-4">
              <el-radio :label="false" size="large">启用</el-radio>
              <el-radio :label="true" size="large">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>
    <select-project :dialog-select="dialogSelectProject" @select-send-close="projectSendClose"></select-project>
    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddOrEdit.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { CreateAppCheckinAuth, UpdateAppCheckinAuth, GetAppCheckinAuthForm } from "@/api/device/index";
import { AppCheckinAuthEditForm } from "@/api/device/types";
import { GetCorpsManager } from "@/api/common/other/index";
import { useScreen } from "@/store/modules/screen";
import SelectProject from "@/views/common/SelectProject/index.vue";
import { FormRules } from "element-plus/es/components/form/src/types";
import moment from "moment";

//声明变量

// 参建单位列表（需要从API获取）
const corps = ref([]);
const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(500);
const itemSpan = ref(12);
const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: 0,
    }),
  },
});
const { dialogAddOrEdit } = toRefs(props);
const emit = defineEmits(["sendClose"]);
const loading = ref(false);

const formData = reactive<AppCheckinAuthEditForm>({
  isDisable: false,
});
const baseFormRef = ref(ElForm);
const dialogSelectProject = reactive({
  visible: false,
  title: "选择项目",
  footBtn: "确认",
  id: 0,
  type: "allproject",
});

const handleSelectProject = function () {
  dialogSelectProject.visible = true;
};

const projectSendClose = function (info: any) {
  formData.corpId = undefined;
  formData.corpName = "";
  dialogSelectProject.visible = false;
  if (info) {
    formData.projectName = info.name;
    formData.projectId = info.projectId;
    initCorps(info.projectId);
  }
  // else {
  //   corps.value = [];
  // }
};

const initCorps = function (projectId: number) {
  GetCorpsManager({ projectId: projectId }).then((res) => {
    if (res.type === 0) {
      if (res.success) {
        corps.value = res.data.list;
        // alert(JSON.stringify(res.data.list));
      } else {
      }
    } else {
    }
  });
};
//改变选择单位回调
const changeCorp = function (val: any) {
  let temp = corps.value.filter((item: { corpId: string }) => item.corpId == val);
  if (temp.length > 0) {
    formData.corpId = temp[0].corpId;
    formData.corpName = temp[0].name;
    return;
  }
  formData.corpId = 0;
  formData.corpName = "";
};

const rules = reactive<FormRules<AppCheckinAuthEditForm>>({
  startDate: [{ required: true, message: "开始日期不能为空", trigger: "blur" }],
  endDate: [
    {
      required: true,
      trigger: "blur",
      validator(_rule, value, callback, _source, _options) {
        if (value) {
          if (new Date(value).getTime() < new Date(formData.startDate ?? "").getTime()) {
            callback(new Error("结束日期不能小于开始日期"));
          }
        }
        if (value == "" || value == null || value == undefined || value == "null") {
          callback(new Error("结束日期不能为空"));
        }
        callback();
      },
    },
  ],
  corpName: [{ required: true, message: "参建单位不能为空", trigger: "blur" }],
  projectName: [{ required: true, message: "所属项目不能为空", trigger: "blur" }],
});

//开始时间禁用范围
const disabledStartDate = (time: Date) => {
  return time.getTime() < new Date(moment().add(-1, "days").format("YYYY-MM-DD")).getTime();
};
//结束时间禁用范围
const disabledEndDate = (time: Date) => {
  if (formData.startDate) {
    return time.getTime() <= new Date(formData.startDate).getTime();
  }
  return time.getTime() > new Date(moment().format("YYYY-MM-DD")).getTime();
};

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 500;
    itemSpan.value = 18;
  }
}

onMounted(async () => {
  initScreen();
  if (dialogAddOrEdit.value.id > 0) {
    GetAppCheckinAuthForm(dialogAddOrEdit.value.id).then((res) => {
      if (res.success) {
        Object.assign(formData, res.data);
      }
    });
  }
});

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  baseFormRef.value.resetFields();
  baseFormRef.value.clearValidate();
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  baseFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (formData.corpId == "") formData.corpId = 0;
      if (dialogAddOrEdit.value.id > 0) {
        UpdateAppCheckinAuth(formData)
          .then((resp) => {
            if (resp.type === 0) {
              if (resp.success === true) {
                ElMessage.success(resp.msg);
                closeDialog(true);
              } else {
                ElMessage.warning(resp.msg);
              }
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (loading.value = false));
      } else {
        CreateAppCheckinAuth(formData)
          .then((resp) => {
            if (resp.type === 0) {
              if (resp.success === true) {
                ElMessage.success(resp.msg);
                closeDialog(true);
              } else {
                ElMessage.warning(resp.msg);
              }
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}

:deep(.el-upload__tip) {
  margin-left: 10px;
}

:deep(.el-step.is-simple .el-step__title) {
  font-size: 14px;
}

:deep(.el-steps--simple) {
  padding: 13px 4% !important;
}

:deep(.el-icon svg) {
  height: 1.5em;
  width: 1.5em;
}
</style>
